//
//  AddnoticeViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/4/21.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class AddnoticeViewController: BaseViewController,UITextViewDelegate, UICollectionViewDelegate,UICollectionViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,MBProgressHUDDelegate,AJPhotoPickerProtocol, AJPhotoBrowserDelegate {
    
    var titleField: FUITextField!
    var contentField: UITextView!
    var label: UILabel!
    var switchBT: UISwitch!
    var photoCollectionView: UICollectionView!
    
    var photoArray = NSMutableArray()
    
    let collectionIdentifier = "PhotoCollectionViewCellIdentifier"
    
    
    var hud: MBProgressHUD!
    var baseStr: String!
    var isSend = "true"
    var modetype: String!
    var isSendMsg = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.title = "添加通知"
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "发送", style: UIBarButtonItemStyle.plain, target: self, action: #selector(AddnoticeViewController.Send))
        InitViews()
        
    }
    
    func InitViews() {
        
        titleField = FUITextField.init(frame: CGRect(x: 10, y: 74, width: screenW-20, height: 40))
        titleField.backgroundColor = UIColor.clear
        titleField.textFieldColor = UIColor.white
        titleField.layer.borderColor = UIColor.init(hexString: "f0f0f0", alpha: 1.0).cgColor
        titleField.layer.borderWidth = 1.0
        titleField.layer.cornerRadius = 3.0
        titleField.borderColor = barColor
        titleField.borderWidth = 2.0
        titleField.cornerRadius = 3.0
        titleField.font = UIFont.systemFont(ofSize: 16)
        titleField.edgeInsets = UIEdgeInsetsMake(0.0, 8.0, 0.0, 8.0)
        titleField.placeholder = "请添加通知标题，不能为空"
        
        contentField = UITextView.init(frame: CGRect(x: 10, y: titleField.frame.maxY+10, width: screenW-20, height: 100))
        contentField.backgroundColor = UIColor.init(hexString: "f2f2f2", alpha: 1)
        contentField.textColor = UIColor.darkGray
        contentField.isHidden = false
        contentField.delegate = self;
        contentField.font = UIFont.systemFont(ofSize: 15)
        contentField.tag = 2;
        
        
        label = UILabel.init(frame: CGRect(x: 16, y: titleField.frame.maxY+16, width: screenW - 20, height: 20))
        label.text = "请添加通知内容(200字内)";
        label.textColor = UIColor.init(hexString: "DBDBDB", alpha: 1)
        label.isEnabled = false//lable必须设置为不可用
        label.backgroundColor = UIColor.clear
        label.font = UIFont.systemFont(ofSize: 15)
        
        switchBT = UISwitch(frame: CGRect(x: 10, y: contentField.frame.maxY + 10, width: 50, height: 30))
        switchBT.isOn = false
        switchBT.addTarget(self, action: #selector(AddnoticeViewController.switchBT(_:)), for: UIControlEvents.valueChanged)
        
        let label1 = UILabel(frame: CGRect(x: switchBT.frame.maxX + 10, y: switchBT.frame.minY, width: screenW - 100, height: 30))
        label1.text = "是否发送短信通知"
        label1.textAlignment = NSTextAlignment.left
        label1.font = UIFont.systemFont(ofSize: 16)
        label1.textColor = UIColor.lightGray
        
        photoCollectionView = UICollectionView.init(frame: CGRect(x: 10, y: switchBT.frame.maxY + 10, width: screenW - 20, height: getAddPhotoCollectionHeight(photoArray)), collectionViewLayout: AddPhotoFlowLayout.init())
        photoCollectionView.backgroundColor = UIColor.clear
        photoCollectionView.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: collectionIdentifier)
        photoCollectionView.scrollsToTop = true
        photoCollectionView.delegate = self
        photoCollectionView.dataSource = self
        
        self.view.addSubview(titleField)
        self.view.addSubview(contentField)
        self.view.addSubview(label)
        self.view.addSubview(switchBT)
        self.view.addSubview(label1)
        self.view.addSubview(photoCollectionView)
        
    }
    //MARK: - 判断是否-发送短信
    func switchBT(_ sender: Any) {
        
        let switchBT = sender as! UISwitch
        let send = switchBT.isOn
        
        if send {
            GetRightWithEmail()
            print("发送短信")
        }else {
            isSendMsg = false
            print("不发送短信")
        }
        
    }
    
    func GetRightWithEmail() {

        let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        hud?.animationType = MBProgressHUDAnimation.fade
        let user = getUserPojo()
        let url = "\(server)/webapp/apps/schwebappapi.ashx"
        let dic = ["t" : "32", "sch" : user.schid!, "modetype" : modetype!]
        
        AFNRequestWithMethod(method: Method.POST, url: url, param: dic as NSDictionary, Success: { (response) in
            
//            let dic = response as! NSDictionary
            let json = JSON(response!)
            let type = json["type"].stringValue
            let msg = json["tupemsg"].stringValue
            let num = json["surplusNum"].stringValue
            print("是否有权限:\(type),是否开通:\(msg),剩余条数:\(num)")
            
            if type == "0" {
                self.isSendMsg = false
                self.switchBT.isOn = false
                UIAlertView(title: "提示", message: "学校尚未开通短信功能", delegate: nil, cancelButtonTitle: "知道了").show()
            }else if type == "2" && num == "0" {
                self.isSendMsg = false
                self.switchBT.isOn = false
                UIAlertView(title: "提示", message: "对不起，学校免费短信额度已经用完，请联系管理员", delegate: nil, cancelButtonTitle: "知道了").show()

            }else {
                if type.characters.count > 0 {
                    self.isSendMsg = true
                }else {
                    self.isSendMsg = false
                    self.switchBT.isOn = false
                    UIAlertView(title: "提示", message: "对不起，学校免费短信额度已经用完，请联系管理员", delegate: nil, cancelButtonTitle: "知道了").show()
                }
                
            }
            hud?.hide(true)

            }) { (error) in
                self.isSendMsg = false
                self.switchBT.isOn = false
                UIAlertView(title: "提示", message: "学校尚未开通短信功能", delegate: nil, cancelButtonTitle: "知道了").show()

        }
        
    }
    func textViewDidChange(_ textView: UITextView) {
        if textView.text.characters.count == 0 {
            label.text = "请添加通知内容(200字内)"
        }else{
            label.text = ""
        }
        let length = textView.text.characters.count
        if length > 200 {

        }
    }
   
    //MARK: - collectionView Delegate and data source
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photoArray.count + 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: PhotoCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionIdentifier, for: indexPath) as! PhotoCollectionViewCell
        cell.backgroundColor = UIColor.white
        let count = (indexPath as NSIndexPath).row
        if count == photoArray.count {
            cell.photoImage.image = UIImage.init(named: "hnx")
        }else{
            let assest = photoArray.object(at: count)
            if (assest as AnyObject).isKind(of: UIImage.self) {
                cell.photoImage.image = assest as? UIImage
            }else{
                let ass = assest as! ALAsset
                cell.photoImage.image = UIImage.init(cgImage: ass.aspectRatioThumbnail().takeUnretainedValue())
            }
        }
        
        return cell;
        
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        contentField.resignFirstResponder()
        if (indexPath as NSIndexPath).row == photoArray.count {
            photoAdd()
        }else{
            print("选中第\(indexPath.row+1)张")
            //++++++++++++++++++++++++++++++++
            showBigImage(index: Int(indexPath.row))
            //++++++++++++++++++++++++++++++++
        }
    }
    
    //MARK: - AJPhotoBrowserDelegate
    func photoBrowser(_ vc: AJPhotoBrowserViewController!, deleteWith index: Int) {
        //删除选中的照片
    }
    func photoBrowser(_ vc: AJPhotoBrowserViewController!, didDonePhotos photos: [Any]!) {
        //从相册点击确定
        self.photoArray.removeAllObjects()
        self.photoArray.addObjects(from: photos)
        
        self.photoCollectionView.reloadData()
        vc.dismiss(animated: true, completion: nil)

    }
    func showBigImage(index: Int) {
        var pphotos = [Any]()
        for i in 0..<photoArray.count {
            print("\(i) = \(photoArray.object(at: i))")
            pphotos.append(photoArray[i])
        }
        
        let photoBrowserVC = AJPhotoBrowserViewController.init(photos: pphotos, index: index)
        photoBrowserVC?.delegate = self
        self.present(photoBrowserVC!, animated: true, completion: nil)
    }
    
    func photoAdd() {
        
        //可选过滤
        
        let picker = AJPhotoPickerViewController.init()
        picker.maximumNumberOfSelection = 9
        picker.multipleSelection = true
        picker.assetsFilter = ALAssetsFilter.allPhotos()
        picker.showEmptyGroups = true
        picker.delegate = self
        self.present(picker, animated: true, completion: nil)
        
    }
    
    //MARK: - AJPhotoPicker Protocol
    
    /**
     选中
     
     - parameter picker: <#picker description#>
     - parameter asset:  <#asset description#>
     */
    func photoPicker(_ picker: AJPhotoPickerViewController!, didSelect asset: ALAsset!) {
        
    }
    /**
     取消选中
     
     - parameter picker: <#picker description#>
     - parameter asset:  <#asset description#>
     */
    func photoPicker(_ picker: AJPhotoPickerViewController!, didDeselect asset: ALAsset!) {
        
    }
    /**
     完成
     
     - parameter picker: <#picker description#>
     - parameter assets: <#assets description#>
     */
    //这个警告是个坑、如果按照提示的话、选中图片之后点击右上角的确定按钮没反应、最关键是、真机运行不会通过、直接报错
    func photoPicker(_ picker: AJPhotoPickerViewController!, didSelectAssets assets: [AnyObject]!) {
        photoArray.removeAllObjects()
        photoArray.addObjects(from: assets)
        
        photoCollectionView.frame = CGRect(x: 10, y: switchBT.frame.maxY + 10, width: screenW - 20, height: getAddPhotoCollectionHeight(photoArray))
        photoCollectionView.reloadData()
        
        picker.dismiss(animated: true, completion: nil)
        
    }
    /**
     取消选择
     
     - parameter picker: <#picker description#>
     */
    func photoPickerDidCancel(_ picker: AJPhotoPickerViewController!) {
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    /**
     相机
     
     - parameter picker: <#picker description#>
     */
    func photoPickerTapCameraAction(_ picker: AJPhotoPickerViewController!) {
        if photoArray.count >= 9 {
            TSMessage.showNotification(in: picker, title: "提示", subtitle: "对不起，您选择的图片过多，现在只能支持最大9张图片", image: nil, type: TSMessageNotificationType.error, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
        }else{
            picker.dismiss(animated: false, completion: nil);
            let pickCamer = UIImagePickerController()
            pickCamer.allowsEditing = false
            pickCamer.sourceType = UIImagePickerControllerSourceType.camera
            pickCamer.delegate = self
            pickCamer.cameraFlashMode = UIImagePickerControllerCameraFlashMode.auto
            self.present(pickCamer, animated: true, completion: nil)
        }
        
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let dic: NSDictionary = info as NSDictionary
        let image = dic.object(forKey: UIImagePickerControllerOriginalImage)
        photoArray.add(image!)
        photoCollectionView.frame = CGRect(x: 10, y: switchBT.frame.maxY + 10, width: screenW - 20, height: getAddPhotoCollectionHeight(photoArray))
        photoCollectionView.reloadData()
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    /**
     超过最大
     
     - parameter picker: <#picker description#>
     */
    func photoPickerDidMaximum(_ picker: AJPhotoPickerViewController!) {
        TSMessage.showNotification(in: picker, title: "提示", subtitle: "对不起，您选择的图片过多，现在只能支持最大9张图片", image: nil, type: TSMessageNotificationType.error, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
    }
    
    //MARK: - 点击"发送"通知
    func Send() {
        if isSend == "true" {
            isSend = "false"
            let noticetitle = titleField.text
            print("标题:" + noticetitle! )
            let noticecontent = contentField.text as String
            if noticetitle?.characters.count == 0 || noticecontent.characters.count == 0 {
                let alert: UIAlertView = UIAlertView.init(title: "出错提示", message: "图文通知标题，图片不能为空！", delegate: self, cancelButtonTitle: "知道了")
                alert.show()
                isSend = "true"
            }else{
                titleField.resignFirstResponder()
                contentField.resignFirstResponder()
                hud = MBProgressHUD.showAdded(to: self.view, animated: true)
//                hud.mode = MBProgressHUDMode.Indeterminate
                hud.animationType = MBProgressHUDAnimation.fade
                hud.labelText = "全校通知上传中...请稍候！"
                let queue = DispatchQueue(label: "queue")
                queue.async {
                    var ims = ""
                    if self.photoArray.count != 0 {
                        for i in 0...self.photoArray.count - 1 {
                            var image: UIImage!
                            if (self.photoArray.object(at: i) as AnyObject).isKind(of: UIImage.self){
                                image = self.photoArray.object(at: i) as! UIImage
                            }else{
                                let asset: ALAsset = self.photoArray.object(at: i) as! ALAsset
                                image = UIImage.init(cgImage: asset.defaultRepresentation().fullResolutionImage().takeUnretainedValue())
                            }
                            let picData = UIImageJPEGRepresentation(image, 0.1)
                            print("图片大小\((picData?.count)!/1024)Kb")
                            let picStr: String = (picData?.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters))!
                            if (i==0) {
                                ims = picStr;
                            }else{
                                ims = "\(ims)|\(picStr)"
                            }
                        }
                    }
                    
                    let user = getUserPojo()
                    let request = "\(requestHeader)27</t><uid>\(user.userid!)</uid><title>\(noticetitle!)</title><msg>\(noticecontent)</msg><sch>\(user.schid!)</sch><filetype>1</filetype><base64>\(ims)</base64><SendToUser>all</SendToUser><serid></serid></channel></rss>"
                    print(request)
                    
                    let url = server + adminwebapppi
                    let result = HttpUtils.httpPostUTF(url, with: request)
                    print(result!)
                    DispatchQueue.main.async(execute: {
                        
                        if result == "True" {
                            if self.isSendMsg {
                                
                                let url = "\(server)/webapp/apps/schwebappapi.ashx"
                                let dic = ["t":"33", "sch":user.schid!, "uid":user.userid!, "modetype":self.modetype!, "title":noticecontent, "classid":""]
                                //1209 - 将这个值 "classid" 为空 、表示默认发送给
                                AFNRequestWithMethod(method: Method.POST, url: url, param: dic as NSDictionary, Success: { (response) in
                                    
                                    let dic = response as! NSDictionary
                                    let code = dic.object(forKey: "code") as! String
                                    let msg = dic.object(forKey: "msg") as! String
                                    if code == "2" {
                                        self.hud.hide(true)
                                        self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
                                        self.hud.mode = MBProgressHUDMode.customView
                                        self.hud.labelText = "通知上传成功"
                                        self.hud.customView = UIImageView.init(image: UIImage.init(named: "okbai"))
                                        
                                    }else {
                                        UIAlertView(title: "提示", message: msg, delegate: nil, cancelButtonTitle: "知道了").show()
                                    }

                                    DispatchQueue.global( priority: DispatchQueue.GlobalQueuePriority.low).async(execute: {
                                        sleep(1)
                                        DispatchQueue.main.async(execute: {
                                            self.hud.hide(true)
                                            let index = self.navigationController?.viewControllers.index(of: self)
                                            self.navigationController?.popToViewController((self.navigationController?.viewControllers[index! - 1])!, animated: true)
                                            self.dismiss(animated: true, completion: nil)
                                            
                                            
                                        })
                                    })
                                    
                                    }, Failure: { (error) in
                                        
                                        self.hud.hide(true)
                                        self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
                                        self.hud.mode = MBProgressHUDMode.customView
                                        self.hud.labelText = "通知上传成功,短信发送失败"
                                        self.hud.customView = UIImageView.init(image: UIImage.init(named: "okbai"))
                                        DispatchQueue.global( priority: DispatchQueue.GlobalQueuePriority.low).async(execute: {
                                            sleep(1)
                                            DispatchQueue.main.async(execute: {
                                                self.hud.hide(true)
                                                let index = self.navigationController?.viewControllers.index(of: self)
                                                self.navigationController?.popToViewController((self.navigationController?.viewControllers[index! - 1])!, animated: true)
                                                self.dismiss(animated: true, completion: nil)
                                                
                                                
                                            })
                                        })
                                })
                                
                            }else {
                                self.hud.labelText = "通知上传成功"
                                self.hud.customView = UIImageView.init(image: UIImage.init(named: "okbai"))
                                DispatchQueue.global( priority: DispatchQueue.GlobalQueuePriority.low).async(execute: {
                                    sleep(1)
                                    DispatchQueue.main.async(execute: {
                                        self.hud.hide(true)
                                        let index = self.navigationController?.viewControllers.index(of: self)
                                        self.navigationController?.popToViewController((self.navigationController?.viewControllers[index! - 1])!, animated: true)
                                        self.dismiss(animated: true, completion: nil)
                                        
                                        NotificationCenter.default.post(name: Notification.Name(rawValue: "SchNoticeSendSuccessful"), object: nil, userInfo: nil)
                                    })
                                })

                            }
                            
                        }else{
                            self.hud.labelText = "班级通知上传失败,稍后再试！"
                            self.hud.customView = UIImageView.init(image: UIImage.init(named: "nobai"))
                            DispatchQueue.global( priority: DispatchQueue.GlobalQueuePriority.low).async(execute: {
                                sleep(1)
                                DispatchQueue.main.async(execute: {
                                    self.hud.hide(true)
                                    self.isSend = "true"
                                })
                            })
                        }
                    })

                }
            }
        }else{
            TSMessage.showNotification(in: self, title: "提示", subtitle: "主人，请不要连续点击发送，\(appname)已经在提交了……", image: nil, type: TSMessageNotificationType.error, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
            
        }
        
        
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.titleField.resignFirstResponder()
        self.contentField.resignFirstResponder()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
